package com.jzwl.common.id.dao.impl;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.springframework.stereotype.Component;

import com.jzwl.common.id.dao.SequenceDAO;
/**
 * <p>Title:SequenceDAOImpl </p>
 * 	<p>Description: ID生成器工具类</p>
 * 	<p>Company: </p> 
 * 	@author Administrator 
 * 	@date 2015年8月24日 下午5:35:10
 */
@Component
public class SequenceDAOImpl implements SequenceDAO {
	
	private static final long ONE_STEP = 10;
	private static final Lock LOCK = new ReentrantLock();
	private static long lastTime = System.currentTimeMillis();
	private static short lastCount = 0;
	private static int count = 0;
	
	public String nextId() {
		LOCK.lock();
		try {
			if (lastCount == ONE_STEP) {
				boolean done = false;
				while (!done) {
					long now = System.currentTimeMillis();
					if (now == lastTime) {
						try {
							Thread.currentThread();
							Thread.sleep(1);
						} catch (java.lang.InterruptedException e) {
						}
						continue;
					} else {
						lastTime = now;
						lastCount = 0;
						done = true;
					}
				}
			}
			count = lastCount++;
		} finally {
			LOCK.unlock();
			return lastTime + "" + String.format("%03d", count);
		}
	}

}
